<?php

namespace addons\facrm\controller\facrm;

use addons\facrm\library\BackendApi;
use app\admin\model\AuthGroup;
use app\admin\model\facrm\Contract;
use app\admin\model\facrm\contract\Receivables;
use addons\facrm\model\Admin as AdminModel;
use fast\Tree;

/**
 * 首页
 * @icon fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends BackendApi
{

    protected $groupList = [];
    protected $groupdata = [];
    protected $noNeedRight = ['getAchievement','getNotice'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new AdminModel();
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $this->groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($this->groupList);
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $this->groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $this->groupdata = $result;
        }
    }

    /**
     * 首页数据
     * @ApiMethod (POST|GET)
     * @ApiParams(name="type", type="string", required=true, description="oneself:自己，team团队")
     * @ApiReturnParams    (name="communicate", type="int", required=false, sample="0",description="待跟进客户")
     * @ApiReturnParams    (name="lose_num", type="int", required=false, sample="0",description="将过期客户")
     * @ApiReturnParams    (name="business", type="int", required=false, sample="0",description="待跟进商机")
     * @ApiReturnParams    (name="contract_expire", type="int", required=false, sample="0",description="过期合同")
     * @ApiReturnParams    (name="contract_return", type="int", required=false, sample="0",description="待回款合同")
     * @ApiReturnParams    (name="contract_flow", type="int", required=false, sample="0",description="待审核合同")
     * @ApiReturnParams    (name="receivables_flow", type="int", required=false, sample="0",description="待审核回款")
     * @ApiReturnParams    (name="clues_num", type="int", required=false, sample="0",description="待跟进线索")
     */
    public function index()
    {
        $year = $this->request->param('year', date("Y", time()), 'intval');
        $month = $this->request->param('month', intval(date("m", time())), 'intval');
        $config = $this->request->param('config', 1, 'intval');//$config 1=>'合同金额',2=>'回款金额'
        $group_id = $this->request->param('group_id', 0, 'intval');//部门
        $admin_id = $this->request->param('admin_id', 0, 'intval');//员工
        $type = $this->request->param('type', 'oneself');
        $achievementModel = new \app\admin\model\facrm\Achievement();


        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;

        switch ($type) {
            case 'oneself':
                $return_data=$this->getNotice(true);
                if (!$achievement = $achievementModel->achievement($config, $year, $month, 3, $this->auth->id, $this->auth->id)) {
                    return $this->error($achievementModel->getError());
                }
                $return_data['achievement'] = $achievement;
                //自己的end
                break;
            case 'team':
                $return_data=$this->getNotice(true);
                if ($group_id && !$admin_id) {
                    //如果有选团队并且没有选员工就是团队业绩
                    Tree::instance()->init($this->groupList);
                    $this->childrenGroupIds = Tree::instance()->getChildrenIds($group_id, true);

                    $authGroupList = \app\admin\model\AuthGroupAccess::
                    field('uid,group_id')
                        ->where('group_id', 'in', $this->childrenGroupIds)
                        ->select();
                    $this->childrenAdminIds=[];
                    foreach ($authGroupList as $k => $v) {
                        if ($this->childrenAdminIds && in_array($v['uid'], $this->childrenAdminIds)) continue;
                        $this->childrenAdminIds[] = $v['uid'];
                    }

                } else if($admin_id) {
                    $this->childrenAdminIds = $admin_id ;
                    $this->childrenGroupIds=$admin_id;
                }

                $team_achievement = $achievementModel->achievement($config, $year, $month, 2, $this->childrenGroupIds, $this->childrenAdminIds);
                $team_achievement['config']=$config;
                $return_data =array_merge($return_data,
                    [
                    'achievement' => $team_achievement,
                    ]) ;
                break;
            //团队的end
            default:
                return $this->error(__("访问有误"));
        }

        return $this->success('', $return_data);


    }

    /**
     * 消息和提醒
     * @ApiParams(name="type", type="string", required=true, description="oneself:自己，team团队")
     * @ApiReturnParams    (name="communicate", type="int", required=false, sample="0",description="待跟进客户")
     * @ApiReturnParams    (name="lose_num", type="int", required=false, sample="0",description="将过期客户")
     * @ApiReturnParams    (name="business", type="int", required=false, sample="0",description="待跟进商机")
     * @ApiReturnParams    (name="contract_expire", type="int", required=false, sample="0",description="过期合同")
     * @ApiReturnParams    (name="contract_return", type="int", required=false, sample="0",description="待回款合同")
     * @ApiReturnParams    (name="contract_flow", type="int", required=false, sample="0",description="待审核合同")
     * @ApiReturnParams    (name="receivables_flow", type="int", required=false, sample="0",description="待审核回款")
     * @ApiReturnParams    (name="clues_num", type="int", required=false, sample="0",description="待跟进线索")
     * @ApiReturnParams    (name="invoice_flow", type="int", required=false, sample="0",description="待审批发票")
     * @ApiReturnParams    (name="invoice_opener", type="int", required=false, sample="0",description="待开具发票")
     */
    public function getNotice($isReturn=false){
        $type = $this->request->param('type', 'oneself');
        $businessModel = model('\app\admin\model\facrm\Business');
        $customerModel = model('\app\admin\model\facrm\Customer');
        $cluesModel = model('\app\admin\model\facrm\Clues');
        $contractModel = model('\app\admin\model\facrm\Contract');
        $receivablesModel = model('\app\admin\model\facrm\contract\Receivables');
        $invoiceModel = model('\app\admin\model\facrm\Invoice');
        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        switch ($type) {
            case 'oneself':
                //自己的start
                $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                $filter_w['owner_user_id'] = $this->auth->id;

                //需要联系客户
                $communicate = $customerModel->where('next_time', 'between', [1, $end_time])->where($filter_w)->count();

                //待跟进线索
                $clues_num = $cluesModel->where('next_time', 'between', [1, $end_time])->where($filter_w)->count();

                //将要过期的客户
                $lose_num = count($customerModel->getLose($this->auth->id));

                $business = $businessModel->where('next_time', 'between', [1, $end_time])->where($filter_w)->count();
                //是否有合同权限
                $contract_return = $contract_expire = 0;
                if ($this->auth->check('facrm/contract/index')) {
                    $filter_w['check_status'] = 2;
                    //快过期和过期合同
                    $contract_expire = $contractModel->where('end_time', 'between', [1, $end_time + (30 * 86400)])->where('expire_handle', 0)->where($filter_w)->count();
                    //待回款合同
                    $contract_return = $contractModel->where("money", "exp", ">return_money")->where($filter_w)->count();
                }
                //合同审核和回款审核
                $contract_flow = $contractModel->where('find_in_set(:id,flow_admin_id)', ['id' => $this->auth->id])->where('check_status', 'in', [0, 1])->count();
                $receivables_flow = $receivablesModel->where('find_in_set(:id,flow_admin_id)', ['id' => $this->auth->id])->where('check_status', 'in', [0, 1])->count();

                //待审发票
                $invoice_flow=$invoiceModel->where('find_in_set(:id,flow_admin_id)', ['id' => $this->auth->id])->where('check_status', 'in', [0, 1])->count();
                //待开具发票
                $invoice_opener=$invoiceModel->where('status', 'in', [0, 1])->where('check_status', 2)->count();


                $return_data = [
                    'communicate' => $communicate,//待跟进客户
                    'lose_num' => $lose_num, //将过期客户
                    'business' => $business,//待跟进商机
                    'contract_expire' => $contract_expire,//过期合同
                    'contract_return' => $contract_return,//待回款合同
                    'contract_flow' => $contract_flow,//待合同审核
                    'receivables_flow' => $receivables_flow,//待回款审核
                    'clues_num'=>$clues_num,//待跟进线索
                    'invoice_flow'=> $invoice_flow,
                    'invoice_opener'=>$invoice_opener

                ];
                //自己的end
                break;
            case 'team':
                $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                //团队的
                $filter_w = array();
                $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                //需要联系客户
                $team_communicate = $customerModel->where('next_time', 'between', [1, $end_time])->where($filter_w)->count();

                //待跟进线索
                $clues_num = $cluesModel->where('next_time', 'between', [1, $end_time])->where($filter_w)->count();

                //将要过期的用户
                $team_lose_num = count($customerModel->getLose($this->childrenAdminIds));

                $team_business = $businessModel->where('next_time', 'between', [1, $end_time])->where($filter_w)->count();
                //是否有合同权限
                $team_contract_return = $team_contract_expire = 0;
                if ($this->auth->check('facrm/contract/index')) {
                    $filter_w['check_status'] = 2;
                    //快过期和过期合同
                    $team_contract_expire = $contractModel->where('end_time', 'between', [1, $end_time + (30 * 86400)])->where('expire_handle', 0)->where($filter_w)->count();
                    //待回款合同
                    $team_contract_return = $contractModel->where("money", "exp", ">return_money")->where($filter_w)->count();
                }

                $return_data = [
                    'communicate' => $team_communicate,
                    'lose_num' => $team_lose_num,
                    'clues_num'=>$clues_num,//待跟进线索
                    'business' => $team_business,
                    'contract_expire' => $team_contract_expire,
                    'contract_return' => $team_contract_return,
                ];
                break;
            //团队的end
            default:
                return $this->error(__("访问有误"));
        }
        if ($isReturn){
            return  $return_data;
        }

        return $this->success('', $return_data);

    }



}
